package com.qisu.util;

import java.security.Security;
import java.util.Arrays;
import java.util.Properties;

import javax.mail.BodyPart;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import com.sun.net.ssl.internal.ssl.Provider;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;

/**
 * 发送邮件工具
 *
 * @author lijin
 *
 */
public class MailUtils {
	private Log log = LogFactory.get();
	private String _host;
	private String _sender;
	private String _pwd;

	public MailUtils(String host, String sender, String pwd) {
		_host = host;
		_sender = sender;
		_pwd = pwd;
	}

	/**
	 * 发送邮件
	 *
	 * @param title 邮件标题
	 * @param body 邮件内容
	 */
	public void sendMail(String[] recipients, String title, String body) {
		Security.addProvider(new Provider());
		final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

		try {
			Session session = buildTransportSession(SSL_FACTORY);
			MimeMessage message = new MimeMessage(session);

			message.setFrom(new InternetAddress(_sender)); // 加载发件人地址
			addRecipients(message, recipients);
			message.setSubject(title); // 加载标题
			buildBody(body, message); // 设置邮件的文本内容

			send(session, message);
		} catch(Exception e) {
			e.printStackTrace();

			StringBuffer sb = new StringBuffer();

			// @formatter:off
			sb.append("-------------------------------------------------------\n")
					.append(title).append("\n")
					.append(body).append("\n")
					.append("-------------------------------------------------------");
			// @formatter:on

			log.warn(sb.toString());
		}
	}

	// 连接并发送发送
	private void send(Session session, MimeMessage message) throws NoSuchProviderException, MessagingException {
		Transport transport = session.getTransport("smtp");

		transport.connect(_host, _sender, _pwd);
		transport.sendMessage(message, message.getAllRecipients());
		transport.close();
	}

	// 构建邮件内容
	private void buildBody(String body, MimeMessage message) throws MessagingException {
		Multipart multipart = new MimeMultipart(); // 向multipart对象中添加邮件的各个部分内容，包括文本内容和附件
		BodyPart contentPart = new MimeBodyPart();

		contentPart.setText(body);
		multipart.addBodyPart(contentPart);
		message.setContent(multipart);
		message.saveChanges();
	}

	// 添加邮件接收人
	private void addRecipients(MimeMessage message, String[] recipients) throws AddressException, MessagingException {
		Arrays.asList(recipients)
				.parallelStream()
				.distinct()
				.forEach(recipientAddress -> {
					try {
						message.addRecipient(RecipientType.TO, new InternetAddress(recipientAddress));
					} catch(MessagingException e) {
						e.printStackTrace();
					}
				});
	}

	// 建立连接
	@SuppressWarnings("serial")
	private Session buildTransportSession(final String SSL_FACTORY) {
		return Session.getDefaultInstance(new Properties() {
			{
				setProperty("mail.smtp.host", _host);
				setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
				setProperty("mail.smtp.socketFactory.fallback", "false");
				setProperty("mail.smtp.port", "465");
				setProperty("mail.smtp.socketFactory.port", "465");
				setProperty("mail.smtp.auth", "true");
			}
		});
	}
}
